<?php

namespace app\api\controller\wanlshop;

use addons\shopro\library\Wechat;
use addons\shopro\model\UserOauth;
use addons\wanlshop\library\WanlPay\WanlPay;
use app\admin\model\Tickets;
use app\admin\model\wanlshop\AddressSpot;
use app\admin\model\wanlshop\Industy;
use app\admin\model\wanlshop\PayIntegral;
use app\api\model\wanlshop\Auth;
use app\api\model\wanlshop\Third;
use app\common\controller\Api;
use addons\wanlshop\library\EasyWeChat\Easywechat;
use addons\wanlshop\library\WanlChat\WanlChat;

use app\common\exception\UploadException;
use app\common\library\Sms;
use app\common\library\Upload;
use app\common\model\ScoreLog;
use fast\Random;
use fast\Http;

use think\Config;
use think\Db;
use think\Validate;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\api\controller\wanlshop\Separate;
/**
 * WanlShop会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'logout', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'third', 'phone', 'perfect','upload'];
    protected $noNeedRight = ['*'];
    
    public function _initialize()
    {
        parent::_initialize();
        //WanlChat 即时通讯调用
		$this->wanlchat = new WanlChat();
		// Auth 写入
		$this->auth->setAllowFields(['id','username','nickname','mobile','avatar','level','gender','birthday','bio','money','score','successions','maxsuccessions','prevtime','logintime','loginip','jointime']);
		// Auth 读取
		$this->auth->getAllowFields(['id','username','nickname','mobile','avatar','level','gender','birthday','bio','money','score','successions','maxsuccessions','prevtime','logintime','loginip','jointime']);
    }
	
    /**
     * 会员登录
     * @ApiMethod   (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$account = $this->request->post('account');
			$password = $this->request->post('password');
			$client_id = $this->request->post('client_id');
			if (!$account || !$password) {
				$this->error(__('Invalid parameters'));
			}
			$ret = $this->auth->login($account, $password);
			if ($ret) {
			    if($client_id){
			        $this->wanlchat->bind($client_id, $this->auth->id);
			    }
				$this->success(__('Logged in successful'), self::userInfo());
			} else {
				$this->error($this->auth->getError());
			}
		}
		$this->error(__('非法请求'));
    }

    /**
     * 手机验证码登录
     * @ApiMethod   (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$mobile = $this->request->post('mobile');
			$captcha = $this->request->post('captcha');
			$client_id = $this->request->post('client_id');
			if (!$mobile || !$captcha) {
				$this->error(__('Invalid parameters'));
			}
			if (!Validate::regex($mobile, "^1\d{10}$")) {
				$this->error(__('Mobile is incorrect'));
			}
			if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
				$this->error(__('Captcha is incorrect'));
			}
			$user = \app\common\model\User::getByMobile($mobile);
			if ($user) {
				if ($user->status != 'normal') {
					$this->error(__('Account is locked'));
				}
				//如果已经有账号则直接登录
				$ret = $this->auth->direct($user->id);
			} else {
				$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
			}
			if ($ret) {
				Sms::flush($mobile, 'mobilelogin');
				if($client_id){
			        $this->wanlchat->bind($client_id, $this->auth->id);
			    }
				$this->success(__('Logged in successful'), self::userInfo());
			} else {
				$this->error($this->auth->getError());
			}
		}
		$this->error(__('非法请求'));
    }
    
    /**
     * 小程序手机号登录
     * @ApiMethod   (POST)
     * @param string $encryptedData  
     * @param string $iv  
     */
    public function phone()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$post = $this->request->post();
		    if (!isset($post['iv'])) {
		        $this->error(__('获取手机号异常'));
		    }
			// 1.1.9升级 改为Easywechat
			try{
				$auth = Easywechat::app()
					->auth
					->session($post['code']);
			} catch (\Exception $e) {
				$this->error($e->getMessage());
			}
			if(isset($auth['errcode'])){
				$this->error($auth['errmsg']);
			}
		    // 判断third是否存在ID,存在快速登录
			if(isset($auth['unionid'])){
				$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'mp_weixin', 'unionid' => $auth['unionid']]);
			}else{
				$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'mp_weixin', 'openid' => $auth['openid']]);
			}
			
			//如果已经有账号则直接登录
		    if ($third && $third['user_id'] != 0) {
    			$ret = $this->auth->direct($third['user_id']);
		    } else {
    		    // 手机号解码
				try{
					$encryptor = Easywechat::app()
						->encryptor
						->decryptData($auth['session_key'], $post['iv'], $post['encryptedData']);
				} catch (\Exception $e) {
					$this->error($e->getMessage());
				}
                // 开始登录
    		    $mobile = $encryptor['phoneNumber'];
    			$user = \app\common\model\User::getByMobile($mobile);
    			if ($user) {
    				if ($user->status != 'normal') {
    					$this->error(__('Account is locked'));
    				}
    				//如果已经有账号则直接登录
    				$ret = $this->auth->direct($user->id);
    			} else {
    				$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
    			}
		    }
		    if ($ret) {
		        if (isset($post['client_id']) && $post['client_id'] != null) {
    		        $this->wanlchat->bind($post['client_id'], $this->auth->id);
    		    }
    			$this->success(__('Logged in successful'), self::userInfo());
    		} else {
    			$this->error($this->auth->getError());
    		}
		}
		$this->error(__('非法请求'));
    }
    
    
    /**
     * 注册会员
     * @ApiMethod   (POST)
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$mobile = $this->request->post('mobile');
			$code = $this->request->post('captcha');
			$client_id = $this->request->post('client_id');
			if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
				$this->error(__('Mobile is incorrect'));
			}
			$ret = Sms::check($mobile, $code, 'register');
			if (!$ret) {
				$this->error(__('Captcha is incorrect'));
			}
			$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
			if ($ret) {
			    if($client_id){
			        $this->wanlchat->bind($client_id, $this->auth->id);
			    }
				$this->success(__('Sign up successful'), self::userInfo());
			} else {
				$this->error($this->auth->getError());
			}
		}
		$this->error(__('非法请求'));
    }

    /**
     * 注销登录
     */
    public function logout($client_id = null)
    {
        // 踢出即时通讯 1.2.0升级
//		foreach ($this->wanlchat->getUidToClientId($this->auth->id) as $client_id) {
//			$this->wanlchat->destoryClient($client_id);
//		}
        // 退出登录
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     * @ApiMethod   (POST)
	 *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$user = $this->auth->getUser();
			$avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
			if($avatar){
				$user->avatar = $avatar;
			}else{
				$username = $this->request->post('username');
				$nickname = $this->request->post('nickname');
				$bio = $this->request->post('bio');
				// 1.1.9升级 生日和性别并不会提交到后台保存
				$gender = $this->request->post('gender');
				$birthday = $this->request->post('birthday');
				// 1.1.9升级 优化为Easywechat
				if($bio){
//					$bioCheck = true;
//					try{
//					    $security = Easywechat::app()
//							->content_security
//							->checkText($bio);
//						if($security['errcode'] == 87014){
//							$bioCheck = false;
//						}
//					} catch (\Exception $e) {
//						$this->error('内容审核失败：可能后台小程序的appid、appsecret配置错误，具体：'. $e->getMessage());
//					}
//					if(!$bioCheck){
//						$this->error(__('风控审核：签名包含敏感词汇'));
//					}
				}
				if($nickname){
//					$nicknameCheck = true;
//					try{
//					    $security = Easywechat::app()
//							->content_security
//							->checkText($nickname);
//						if($security['errcode'] == 87014){
//							$nicknameCheck = false;
//						}
//					} catch (\Exception $e) {
//						$this->error('内容审核失败：可能后台小程序的appid、appsecret配置错误，具体：'. $e->getMessage());
//					}
//					if(!$nicknameCheck){
//						$this->error(__('风控审核：昵称包含敏感词汇'));
//					}
				}
				if ($username) {
//					$usernameCheck = true;
//					try{
//					    $security = Easywechat::app()
//							->content_security
//							->checkText($username);
//						if($security['errcode'] == 87014){
//							$usernameCheck = false;
//						}
//					} catch (\Exception $e) {
//						$this->error('内容审核失败：可能后台小程序的appid、appsecret配置错误，具体：'. $e->getMessage());
//					}
//					if(!$usernameCheck){
//						$this->error(__('风控审核：用户名包含敏感词汇'));
//					}
					$exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
					if ($exists) {
						$this->error(__('Username already exists'));
					}
					$user->username = $username;
				}
				$user->nickname = $nickname;
				$user->bio = $bio;
				// 1.1.9升级 生日和性别并不会提交到后台保存
				$user->gender = $gender;
                if(!empty($birthday)){
                    $user->birthday = $birthday;

                }

			}
			$user->save();
			$this->success('返回成功',$user);
		}
		$this->error(__('非法请求'));
    }

    /**
     * 修改手机号
     * @ApiMethod   (POST)
     * @param string $email   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$user = $this->auth->getUser();
			$mobile = $this->request->param('mobile');
			$captcha = $this->request->param('captcha');
			if (!$mobile || !$captcha) {
			    $this->error(__('Invalid parameters'));
			}
			if (!Validate::regex($mobile, "^1\d{10}$")) {
			    $this->error(__('Mobile is incorrect'));
			}
			if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
			    $this->error(__('Mobile already exists'));
			}
			$result = Sms::check($mobile, $captcha, 'changemobile');
			if (!$result) {
			    $this->error(__('Captcha is incorrect'));
			}
			$verification = $user->verification;
			$verification->mobile = 1;
			$user->verification = $verification;
			$user->password = $mobile;
            $salt ='12345';
            $user->salt = $salt;
            $user->password = md5(md5($mobile) . $salt);
            $user->mobile = $mobile;
			$user->save();
			Sms::flush($mobile, 'changemobile');
			$this->success();
		}
		$this->error(__('非法请求'));
    }
    
    /**
     * 重置密码
     * @ApiMethod   (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$mobile = $this->request->post("mobile");
			$newpassword = $this->request->post("newpassword");
			$captcha = $this->request->post("captcha");
			if (!$newpassword || !$captcha || !$mobile) {
				$this->error(__('Invalid parameters'));
			}
			if (!Validate::regex($mobile, "^1\d{10}$")) {
				$this->error(__('Mobile is incorrect'));
			}
			$user = \app\common\model\User::getByMobile($mobile);
			if (!$user) {
				$this->error(__('User not found'));
			}
			$ret = Sms::check($mobile, $captcha, 'resetpwd');
			if (!$ret) {
				$this->error(__('Captcha is incorrect'));
			}
			Sms::flush($mobile, 'resetpwd');
			//模拟一次登录
			$this->auth->direct($user->id);
			$ret = $this->auth->changepwd($newpassword, '', true);
			if ($ret) {
				$this->success(__('Reset password successful'));
			} else {
				$this->error($this->auth->getError());
			}
		}
		$this->error(__('非法请求'));
    }
    
    /**
     * 第三方登录-web登录
     * @ApiMethod   (POST)
     * @param string $platform 平台名称
     */
    public function third_web()
    {
        $this->error(__('暂未开放'));
    }
    
    
    /**
     * 第三方登录
     * @ApiMethod   (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			// 获取登录配置
			$config = get_addon_config('wanlshop');
			// 获取前端参数
			$post = $this->request->post();
			// 登录项目
			$time = time();
			$platform = $post['platform'];
			// 开始登录
			switch ($platform)
			{
				// 微信小程序登录
				case 'mp_weixin':
					// 1.1.9升级 改为Easywechat
					try{
						$auth = Easywechat::app()
							->auth
							->session($post['loginData']['code']);
					} catch (\Exception $e) {
						$this->error($e->getMessage());
					}
					if(isset($auth['errcode'])){
						$this->error($auth['errmsg']);
					}
					if(isset($auth['unionid'])){
						$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'unionid' => $auth['unionid']]);
					}else{
						$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'openid' => $auth['openid']]);
					}
					// 成功登录
					if ($third) {
					    $user = model('app\common\model\User')->get($third['user_id']);
					    if (!$user) {
					        $this->success('尚未绑定用户', [
					            'binding' => 0,
					            'token' => $third['token']
					        ]);
					    }
					    $third->save([
					        'access_token' => $auth['session_key'],
					        'expires_in' => 7776000,
					        'logintime' => $time,
					        'expiretime' => $time + 7776000
					    ]);
					    $ret = $this->auth->direct($user->id);
					    if ($ret) {
						    if (isset($post['client_id']) && $post['client_id'] != null) {
						        $this->wanlchat->bind($post['client_id'], $this->auth->id);
						    }
							$this->success(__('Sign up successful'), self::userInfo());
						} else {
							$this->error($this->auth->getError());
						}
					} else {
					    // 新增$third
					    $third = model('app\api\model\wanlshop\Third');
					    $third->platform  = 'weixin_open';
						if(isset($auth['unionid'])){
							$third->unionid  = $auth['unionid'];
						}else{
							$third->openid  = $auth['openid'];
						}
					    $third->access_token  = $auth['session_key'];
					    $third->expires_in  = 7776000;
					    $third->logintime  = $time;
					    $third->expiretime  = $time + 7776000;
					    // 判断当前是否登录
					    if($this->auth->isLogin()){
							if (isset($post['client_id']) && $post['client_id'] != null) {
							    $this->wanlchat->bind($post['client_id'], $this->auth->id);
							}
					        $third->user_id  = $this->auth->id;
					        $third->save();
					        // 直接绑定自动完成
					        $this->success('绑定成功', [
					            'binding' => 1
					        ]);
					    } else {
							$third->token  = Random::uuid();
					        $third->save();
					        // 通知客户端绑定
					        $this->success('尚未绑定用户', [
					            'binding' => 0,
					            'token' => $third->token
					        ]);
					    }
					}
					break;
					
				// 微信App登录
				case 'app_weixin':
					$params = [
						'access_token' => $post['loginData']['authResult']['access_token'],
						'openid' => $post['loginData']['authResult']['openid']
					];
					$result = Http::sendRequest("https://api.weixin.qq.com/sns/userinfo", $params, 'GET');
					if ($result['ret']) {
					    $json = (array)json_decode($result['msg'], true);
						if(isset($json['unionid'])){
							$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'unionid' => $json['unionid']]);
						}else{
							$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'openid' => $json['openid']]);
						}
					    // 成功登录
                        if ($third) {
                            $third->save([
                                'access_token' => $post['loginData']['authResult']['access_token'],
                                'refresh_token' => $post['loginData']['authResult']['refresh_token'],
                                'expires_in' => $post['loginData']['authResult']['expires_in'],
                                'logintime' => $time,
                                'expiretime' => $time + $post['loginData']['authResult']['expires_in']
                            ]);
                            $ret = $this->auth->direct($third['user_id']);
                            if ($ret) {
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                    		        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                    		    }
                				$this->success(__('Sign up successful'), self::userInfo());
                			} else {
                				$this->error($this->auth->getError());
                			}
                        } else {
                            // 新增$third
                            $third = model('app\api\model\wanlshop\Third');
                            $third->platform  = 'weixin_open';
							if(isset($json['unionid'])){
								$third->unionid  = $json['unionid'];
							}else{
								$third->openid  = $json['openid'];
							}
                            $third->access_token  = $post['loginData']['authResult']['access_token'];
                            $third->refresh_token  = $post['loginData']['authResult']['refresh_token'];
                            $third->expires_in  = $post['loginData']['authResult']['expires_in'];
                            $third->logintime  = $time;
                            $third->expiretime  = $time + $post['loginData']['authResult']['expires_in'];
                            // 判断当前是否登录,否则注册
                            if($this->auth->isLogin()){
								if (isset($post['client_id']) && $post['client_id'] != null) {
								    $this->wanlchat->bind($post['client_id'], $this->auth->id);
								}
                                $third->user_id  = $this->auth->id;
                                $third->save();
                                // 直接绑定自动完成
                                $this->success('绑定成功', [
                                    'binding' => 1
                                ]);
                            } else {
                                $username = $json['nickname'];
								$auth = [];
                                $mobile = '';
                                $gender = $json['sex'] == 1 ? 1 : 0;
                                $avatar = $json['headimgurl'];
								// 1.1.3升级
								if(isset($json['unionid'])){
									// 1.1.3升级 查询其他unionid的user_id进行登录
									$unionid = model('app\api\model\wanlshop\Third')
									    ->where('user_id','<>', 0)
									    ->where('unionid','=', $json['unionid'])
									    ->find();
									if($unionid){
										$auth = $this->auth->direct($unionid['user_id']);
									}else{
										// 注册账户
										$auth = $this->auth->register('u_'.Random::alnum(6), Random::alnum(), '', $mobile, [
										    'gender' => $gender, 
										    'nickname' => $username, 
										    'avatar' => $avatar
										]);
									}
								}else{
									// 注册账户
									$auth = $this->auth->register('u_'.Random::alnum(6), Random::alnum(), '', $mobile, [
									    'gender' => $gender, 
									    'nickname' => $username, 
									    'avatar' => $avatar
									]);
								}
                    			if ($auth) {
                    			    if (isset($post['client_id']) && $post['client_id'] != null) {
                        		        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                        		    }
                    				// 更新第三方登录
                    			    $third->user_id  = $this->auth->id;
                    			    $third->openname  = $username;
                    			    $third->save();
                    				$this->success(__('Sign up successful'), self::userInfo());
                    			} else {
                    				$this->error($this->auth->getError());
                    			}
                            }
                        }
					}else{
					    $this->error('API异常，App登录失败'); 
					}
					break;
				// 微信公众号登录
				case 'h5_weixin':
					$params = [
					    'appid'      => $config['sdk_qq']['gz_appid'],
					    'secret'     => $config['sdk_qq']['gz_secret'],
					    'code'       => $post['code'],
					    'grant_type' => 'authorization_code'
					];
					$result = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');
					if ($result['ret']) {
						$access = (array)json_decode($result['msg'], true);
						//获取用户信息
						$queryarr = [
							"access_token" => $access['access_token'],
							"openid"       => $access['openid'],
						];
						$ret = Http::sendRequest("https://api.weixin.qq.com/sns/userinfo", $queryarr, 'GET');

						if ($ret['ret']) {
							$json = (array)json_decode($ret['msg'], true);
                            //下方为原逻辑
//							if(isset($json['unionid'])){
//								$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_h5', 'unionid' => $json['unionid']]);
//							}else{
//								$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_h5', 'openid' => $json['openid']]);
//							}
                            if(isset($json['unionid'])){
                                $third = UserOauth::get(['platform' => 'wxOfficialAccount', 'openid' => $json['openid']]);
                            }else{
                                $third = UserOauth::get(['platform' => 'wxOfficialAccount', 'openid' => $json['openid']]);
                            }
							// 成功登录
							if ($third) {
                                model('app\api\model\wanlshop\Third')->save([
                                    'unionid' => $json['unionid'],
									'openid' => $json['openid'], // 1.1.2升级
							        'access_token' => $access['access_token'],
							        'refresh_token' => $access['refresh_token'],
							        'expires_in' => $access['expires_in'],
							        'logintime' => $time,
							        'expiretime' => $time + $access['expires_in']
							    ],['openid'=>$third['openid']]);
                                $third->save([
                                   'unionid'=>$json['unionid']
                                ]);
								// 登录客户端
							    $ret = $this->auth->direct($third['user_id']);
							    if ($ret) {
							        if (isset($post['client_id']) && $post['client_id'] != null) {
								        $this->wanlchat->bind($post['client_id'], $this->auth->id);
								    }
									$this->success(__('Sign up successful'), self::userInfo());
								} else {
									$this->error($this->auth->getError());
								}
							} else {
							    // 新增$third
							    $third = model('app\api\model\wanlshop\Third');
							    $third->platform  = 'weixin_h5';
								// 1.1.2升级
								if(isset($json['unionid'])){
									$third->unionid  = $json['unionid'];
									$third->openid  = $json['openid'];
								}else{
									$third->openid  = $json['openid'];
								}
							    $third->access_token  = $access['access_token'];
							    $third->refresh_token  = $access['refresh_token'];
							    $third->expires_in  = $access['expires_in'];
							    $third->logintime  = $time;
							    $third->expiretime  = $time + $access['expires_in'];
							    // 获取到的用户信息
							    $username = $json['nickname'];
								$auth = [];
							    $mobile = '';
							    $gender = $json['sex'] == 1 ? 1 : 0;
							    $avatar = $json['headimgurl'];
								
//								// 1.1.3升级
//								if(isset($json['unionid'])){
//									// 1.1.3升级 查询其他unionid的user_id进行登录
//									$unionid = model('app\api\model\wanlshop\Third')
//									    ->where('user_id','<>', 0)
//									    ->where('unionid','=', $json['unionid'])
//									    ->find();
//
//									if($unionid){
//										$auth = $this->auth->direct($unionid['user_id']);
//									}else{
//										// 注册账户
//										$auth = $this->auth->register('u_'.Random::alnum(6), Random::alnum(), '', $mobile, [
//										    'gender' => $gender,
//										    'nickname' => $username,
//										    'avatar' => $avatar
//										]);
//									}
//								}else{
									// 注册账户
									$auth = $this->auth->register('u_'.Random::alnum(6), Random::alnum(), '', $mobile, [
									    'gender' => $gender, 
									    'nickname' => $username, 
									    'avatar' => $avatar
									]);
//								}
								
							    if ($auth) {
							        if (isset($post['client_id']) && $post['client_id'] != null) {
							            $this->wanlchat->bind($post['client_id'], $this->auth->id);
							        }
							    	// 更新第三方登录
							        $third->user_id  = $this->auth->id;
							        $third->openname  = $username;
							        $third->save();
                                    $UserOauth = [
                                        'user_id'   =>  $this->auth->id,
                                        'provider'   =>  'Wechat',
                                        'platform'   =>  'wxOfficialAccount',
                                        'nickname'   =>  $username,
                                        'headimgurl'   =>  $avatar,
                                    ];
                                    if(isset($json['unionid'])){
                                        $UserOauth['unionid']  = $json['unionid'];
                                        $UserOauth['openid']  = $json['openid'];
                                    }else{
                                        $UserOauth['openid']  = $json['openid'];
                                    }
                                    (new UserOauth())->save($UserOauth);
							    	$this->success(__('Sign up successful'), self::userInfo());
							    } else {
							    	$this->error($this->auth->getError());
							    }
							}
						}else{
							$this->error('获取用户信息失败！'); 
						}
					}else{
						$this->error('获取openid失败！'); 
					}
					break;
				// QQ小程序登录
				case 'mp_qq':
					$params = [
						'appid'      => $config[$platform]['appid'],
						'secret'     => $config[$platform]['appsecret'],
						'js_code'    => $post['loginData']['code'],
						'grant_type' => 'authorization_code'
					];
					$result = Http::sendRequest("https://api.q.qq.com/sns/jscode2session", $params, 'GET');
					if ($result['ret']) {
					    $json = (array)json_decode($result['msg'], true);
						if(isset($json['unionid'])){
							$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'qq_open', 'unionid' => $json['unionid']]);
						}else{
							$third = model('app\api\model\wanlshop\Third')->get(['platform' => 'qq_open', 'openid' => $json['openid']]);
						}
                        // 成功登录
                        if ($third) {
                            $user = model('app\common\model\User')->get($third['user_id']);
                            if (!$user) {
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third['token']
                                ]);
                            }
                            $third->save([
                                'access_token' => $json['session_key'],
                                'expires_in' => 7776000,
                                'logintime' => $time,
                                'expiretime' => $time + 7776000
                            ]);
                            $ret = $this->auth->direct($user->id);
                            if ($ret) {
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                    		        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                    		    }
                				$this->success(__('Sign up successful'), self::userInfo());
                			} else {
                				$this->error($this->auth->getError());
                			}
                        } else {
                            // 新增$third
                            $third = model('app\api\model\wanlshop\Third');
                            $third->platform  = 'qq_open';
							if(isset($json['unionid'])){
								$third->unionid  = $json['unionid'];
							}else{
								$third->openid  = $json['openid'];
							}
                            $third->access_token  = $json['session_key'];
                            $third->expires_in  = 7776000;
                            $third->logintime  = $time;
                            $third->expiretime  = $time + 7776000;
                            // 判断当前是否登录
                            if($this->auth->isLogin()){
								// 1.1.4升级
								if (isset($post['client_id']) && $post['client_id'] != null) {
								    $this->wanlchat->bind($post['client_id'], $this->auth->id);
								}
                                $third->user_id  = $this->auth->id;
                                $third->save();
                                // 直接绑定自动完成
                                $this->success('绑定成功', [
                                    'binding' => 1
                                ]);
                            } else {
								$third->token  = Random::uuid();
                                $third->save();
                                // 通知客户端绑定
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third->token
                                ]);
                            }
                        }
					}else{
						$this->error('API异常，微信小程序登录失败'); 
					}
					break; 
					
				// QQ App登录
				case 'app_qq':
					$params = [
						'access_token' => $post['loginData']['authResult']['access_token']
					];
					$options = [
                        CURLOPT_HTTPHEADER  => [
                            'Content-Type: application/x-www-form-urlencoded'
                        ]
                    ];
					$result = Http::sendRequest("https://graph.qq.com/oauth2.0/me", $params, 'GET' ,$options);
					if ($result['ret']) {
					    $json = (array)json_decode(str_replace(" );","",str_replace("callback( ","",$result['msg'])), true);
					    if ($json['openid'] == $post['loginData']['authResult']['openid']) {
				            $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'qq_open', 'openid' => $json['openid']]);
    				        if ($third) {
    				            $user = model('app\common\model\User')->get($third['user_id']);
                                if (!$user) {
                                    $this->success('尚未绑定用户', [
                                        'binding' => 0,
                                        'token' => $third['token']
                                    ]);
                                }
    				            $third->save([
                                    'access_token' => $post['loginData']['authResult']['access_token'],
                                    'expires_in' => $post['loginData']['authResult']['expires_in'],
                                    'logintime' => $time,
                                    'expiretime' => $time + $post['loginData']['authResult']['expires_in']
                                ]);
                                $ret = $this->auth->direct($third['user_id']);
                                if ($ret) {
                                    if (isset($post['client_id']) && $post['client_id'] != null) {
                        		        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                        		    }
                    				$this->success(__('Sign up successful'), self::userInfo());
                    			} else {
                    				$this->error($this->auth->getError());
                    			}
    				        } else {
    				            // 新增$third
                                $third = model('app\api\model\wanlshop\Third');
                                $third->platform  = 'qq_open';
                                $third->openid  = $json['openid'];
                                $third->access_token  = $post['loginData']['authResult']['access_token'];
                                $third->expires_in  = $post['loginData']['authResult']['expires_in'];
                                $third->logintime  = $time;
                                $third->expiretime  = $time + $post['loginData']['authResult']['expires_in'];
                                // 判断当前是否登录
                                if($this->auth->isLogin()){
									if (isset($post['client_id']) && $post['client_id'] != null) {
									    $this->wanlchat->bind($post['client_id'], $this->auth->id);
									}
                                    $third->user_id  = $this->auth->id;
                                    $third->save();
                                    // 直接绑定自动完成
                                    $this->success('绑定成功', [
                                        'binding' => 1
                                    ]);
                                } else {
									$third->token  = Random::uuid();
                                    $third->save();
                                    // 通知客户端绑定
                                    $this->success('尚未绑定用户', [
                                        'binding' => 0,
                                        'token' => $third->token
                                    ]);
                                }
    				        }
					    } else {
					        $this->error(__('非法请求，机器信息已提交'));
					    }
					}else{
					    $this->error('API异常，App登录失败'); 
					}
					break;
				// QQ 网页登录
				case 'h5_qq':
					// 后续版本上线
					break; 
				// 微博App登录
				case 'app_weibo':
					$params = [
						'access_token' => $post['loginData']['authResult']['access_token']
					];
					$options = [
                        CURLOPT_HTTPHEADER  => [
                            'Content-Type: application/x-www-form-urlencoded'
                        ],
                        CURLOPT_POSTFIELDS => http_build_query($params),
                        CURLOPT_POST => 1
                    ];
					$result = Http::post("https://api.weibo.com/oauth2/get_token_info", $params, $options);
					$json = (array)json_decode($result, true);
				    if($json['uid'] == $post['loginData']['authResult']['uid']){
				        $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weibo_open', 'openid' => $json['uid']]);
				        if ($third) {
				            $user = model('app\common\model\User')->get($third['user_id']);
                            if (!$user) {
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third['token']
                                ]);
                            }
				            $third->save([
                                'access_token' => $post['loginData']['authResult']['access_token'],
                                'expires_in' => $json['expire_in'],
                                'logintime' => $json['create_at'],
                                'expiretime' => $json['create_at'] + $json['expire_in']
                            ]);
                            $ret = $this->auth->direct($third['user_id']);
                            if ($ret) {
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                    		        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                    		    }
                				$this->success(__('Sign up successful'), self::userInfo());
                			} else {
                				$this->error($this->auth->getError());
                			}
				        } else {
				            // 新增$third
                            $third = model('app\api\model\wanlshop\Third');
                            $third->platform  = 'weibo_open';
                            $third->openid  = $json['uid'];
                            $third->access_token  = $post['loginData']['authResult']['access_token'];
                            $third->expires_in  = $json['expire_in'];
                            $third->logintime  = $json['create_at'];
                            $third->expiretime  = $json['create_at'] + $json['expire_in'];
                            // 判断当前是否登录
                            if($this->auth->isLogin()){
								// 1.1.4升级
								if (isset($post['client_id']) && $post['client_id'] != null) {
								    $this->wanlchat->bind($post['client_id'], $this->auth->id);
								}
                                $third->user_id  = $this->auth->id;
                                $third->save();
                                // 直接绑定自动完成
                                $this->success('绑定成功', [
                                    'binding' => 1
                                ]);
                            } else {
								$third->token  = Random::uuid();
                                $third->save();
                                // 通知客户端绑定
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third->token
                                ]);
                            }
				        }
				    }else{
				        $this->error(__('非法请求，机器信息已提交'));
				    }
					break; 
					
				// 小米App登录
				case 'app_xiaomi':
					
					break;
					
				// 苹果登录
				case 'apple':
					// 后续版本上线
					break; 
				default:
					$this->error('暂并不支持此方法登录');
			}
		}
		$this->error(__('10086非正常请求'));
    }

    /**
	 * 进一步完善资料
	 * @ApiMethod   (POST)
	 */
	public function perfect()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
		    $post = $this->request->post();
			
		    // 判断token没有绑定 1.1.4升级
		    $third = model('app\api\model\wanlshop\Third')
				->where('token', '=', $post['token'])
				->find();
				
		    // 当user_id 不为空可以绑定
    		if($third['user_id'] == 0 && $third){
    		    $username = $post['nickName'];
				$auth = [];
    		    $mobile = '';
    		    $gender = $post['gender'];
        	    $avatar = $post['avatarUrl'];
				// 1.1.9升级
				if ($username) {
					$usernameCheck = true;
					try{
					    $security = Easywechat::app()
							->content_security
							->checkText($username);
						if($security['errcode'] == 87014){
							$usernameCheck = false;
						}
					} catch (\Exception $e) {
						$this->error('内容审核失败：可能后台小程序的appid、appsecret配置错误，具体：'. $e->getMessage());
					}
					if(!$usernameCheck){
						$this->error(__('风控审核：用户名包含敏感词汇'));
					}
				}
				// 1.1.4升级
				if($third['unionid']){
					// 1.1.3升级 查询其他unionid的user_id进行登录
					$unionid = model('app\api\model\wanlshop\Third')
					    ->where('id','<>', $third['id'])
					    ->where('unionid','=', $third['unionid'])
					    ->find();
					if($unionid){
						$auth = $this->auth->direct($unionid['user_id']);
					}else{
						$auth = $this->auth->register('u_'.Random::alnum(6), Random::alnum(), '', $mobile, [
						    'gender' => $gender, 
						    'nickname' => $username, 
						    'avatar' => $avatar
						]);
					}
				}else{
					$auth = $this->auth->register('u_'.Random::alnum(6), Random::alnum(), '', $mobile, [
					    'gender' => $gender, 
					    'nickname' => $username, 
					    'avatar' => $avatar
					]);
				}
        		if ($auth) {
					// 1.1.4升级
					if (isset($post['client_id']) && $post['client_id'] != null) {
					    $this->wanlchat->bind($post['client_id'], $this->auth->id);
					}
        			// 更新第三方登录
        			$third->save([
        		        'user_id' => $this->auth->id,
        		        'openname' => $username
        		    ]);
        			$this->success(__('Sign up successful'), self::userInfo());
        		} else {
        			$this->error($this->auth->getError());
        		}
    		}else{
    		    $this->error(__('非法请求，机器信息已提交'));
    		}
		}
		$this->error(__('非法请求'));
	}
	
	/**
	 * 刷新用户中心
	 * @ApiMethod   (POST)
	 */
	public function refresh()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$this->success(__('刷新成功'), self::userInfo());
		}
		$this->error(__('非法请求'));
	}
	
	/**
	 * 数据统计 - 内部使用，开发者不要调用
	 */
	private function userInfo()
	{
		$user_id = $this->auth->id;
		// 查询订单
		$order = model('app\api\model\wanlshop\Order')
			->where('user_id', $user_id)
			->select();
		$orderCount = array_count_values(array_column($order,'state'));
		
		// 物流列表
		$logistics = [];
		foreach ($order as $value)
		{
			if($value['state'] >=3 && $value['state'] <=6){
				//需要查询的订单
			}
		}
		// 统计数量
		$collection = [];
		$concern = [];
		// 1.1.0升级
		$footgoodsprint = [];
		$footgroupsprint = [];
		foreach (model('app\api\model\wanlshop\GoodsFollow')->where('user_id', $user_id)->select() as $row) {
			if($row['goods_type'] === 'goods'){
				if(model('app\api\model\wanlshop\Goods')->get($row['goods_id'])){
					$collection[] = $row['id'];
				}
			}else if($row['goods_type'] === 'groups'){
				if(model('app\api\model\wanlshop\groups\Goods')->get($row['goods_id'])){
					$collection[] = $row['id'];
				}
			}
		}
		// 1.0.8升级  通过uuid查询足迹
		$uuid = $this->request->server('HTTP_UUID');
		if(!isset($uuid)){
			$charid = strtoupper(md5($this->request->header('user-agent').$this->request->ip()));
			$uuid = substr($charid, 0, 8).chr(45).substr($charid, 8, 4).chr(45).substr($charid,12, 4).chr(45).substr($charid,16, 4).chr(45).substr($charid,20,12);
		}
		foreach (model('app\api\model\wanlshop\Record')->where('uuid', $uuid)->select() as $row) {
			if($row['goods_type'] === 'goods'){
				if(model('app\api\model\wanlshop\Goods')->get($row['goods_id'])){
					$footgoodsprint[] = $row['goods_id'];
				}
			}else if($row['goods_type'] === 'groups'){
				if(model('app\api\model\wanlshop\groups\Goods')->get($row['goods_id'])){
					$footgroupsprint[] = $row['goods_id'];
				}
			}
		}
		
		// 查询动态 、收藏夹、关注店铺、足迹、红包卡券
		$finish =  isset($orderCount[6]) ? $orderCount[6] : 0;
		$pay = isset($orderCount[1]) ? $orderCount[1] : 0;
		$delive = isset($orderCount[2]) ? $orderCount[2] : 0;
		$receiving = isset($orderCount[3]) ? $orderCount[3] : 0;
		$evaluate = isset($orderCount[4]) ? $orderCount[4] : 0;
		// 订单状态:1=待支付,2=待成团,3=待发货,4=待收货,5=待评论,6=已完成,7=已取消
		$groups = model('app\api\model\wanlshop\groups\Order')
			->where('user_id', 'eq', $user_id)
			->where('state', 'neq', 7)
			->count();
	    return [
			'userinfo' => $this->auth->getUserinfo(),
			'statistics' => [
				'dynamic' => [
					'collection' => count($collection),
					'concern' => model('app\api\model\wanlshop\find\Follow')->where('user_id', $user_id)->count(),
					'footprint' => count(array_flip($footgoodsprint)) + count(array_flip($footgroupsprint)),
					'coupon' => model('app\api\model\wanlshop\CouponReceive')->where(['user_id' => $user_id, 'state' => '1'])->count(),
                    'coupons' => model('app\api\model\wanlshop\Coupon')->count(),
					'accountbank' => model('app\api\model\wanlshop\PayAccount')->where('user_id', $user_id)->count()
				],
				'order' => [
					'whole' => $finish + $pay + $delive + $receiving + $evaluate,
					'groups' => $groups,
					'pay' => $pay,
					'delive' => $delive,
					'receiving' => $receiving,
					'evaluate' => $evaluate,
					// 1.1.6升级 退款状态:0=申请退款,1=卖家同意,2=卖家拒绝,3=申请平台介入,4=成功退款,5=退款已关闭,6=已提交物流,7=第三方退款中,8=退款失败
					'customer' => model('app\api\model\wanlshop\Refund')->where(['state' => ['in','0,1,2,3,6,7,8'], 'user_id' => $this->auth->id])->count()
				],
				'logistics' => $logistics
			]
		];
	}
	
	/**
	 * 获取评论列表
	 *
	 * @ApiSummary  (WanlShop 获取我的所有评论)
	 * @ApiMethod   (GET)
	 * 
	 * @param string $list_rows  每页数量
	 * @param string $page  当前页
	 */
	public function comment()
	{
		$list = model('app\api\model\wanlshop\GoodsComment')
			->where('user_id', $this->auth->id)
			->field('id,images,score,goods_id,order_goods_id,state,content,createtime')
			->order('createtime desc')
			->paginate()
			->each(function($data, $key){
				$data['order_goods'] = $data->order_goods ? $data->order_goods->visible(['id','title','image','price']):'';
				return $data;
			});
		$this->success('返回成功', $list);
	}
	
	/**
	 * 获取积分明细
	 */
	public function scoreLog()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$list = model('app\common\model\ScoreLog')
				->where('user_id', $this->auth->id)
				->order('createtime desc')
				->paginate();
			$this->success('ok',$list);
		}
		$this->error(__('非法请求'));
	}
	public function infoUser()
    {
        $user_id = $this->auth->id;
        $user = \app\common\model\User::where('id',$user_id)->find();
        $this->success('请求成功',$user);
    }
    public function merRegistration()
    {
        $data = $this->request->param();
        if (is_numeric($data['qualification_type'])) {
            $industy = Industy::where('id',$data['qualification_type'])->find();
            $data['qualification_type'] = $industy['industry_name'];
        }else{
            $data['qualification_type'] = '电商平台';
        }
        $data['name'] = $data['contact_name'];
        $data['number'] = $data['contact_id_number'];
        $data['mobile'] = $data['mobile_phone'];
        $data['image'] = $data['license_copy'];
        $data['bank_name'] = $data['bank_name'] ? $data['bank_name']:$data['account_bank'];
        $data['verify'] = 2;
        $data['state'] = $data['state'] ? $data['state'] : '1';
        $data['user_id'] = $this->auth->id;
        $data['contact_type'] = 'LEGAL';
        $data['contact_id_doc_type'] = 'IDENTIFICATION_TYPE_IDCARD';
        if($data['spot_type'] == 1){
            unset($data['address']);
            unset($data['time']);
            unset($data['pointLat']);
            unset($data['pointLng']);
            unset($data['spot_type']);
            $auth = Auth::where('user_id',$data['user_id'])->find();
            if($auth){
                $auth = Auth::where('user_id',$data['user_id'])->update($data);
            }else{
                $auth = Auth::create($data);
            }
        }else{
            unset($data['spot_type']);
            $user = \app\admin\model\User::where('id',$data['user_id'])->find();
            unset($data['state']);
            unset($data['shop_type']);
            $data['img'] = $data['avatar'];
            $data['spot_type'] = $data['type'];
            unset($data['type']);
            $data['name'] = $data['shopname'];
            $data['phone'] = $data['mobile'];
            $data['contacts'] = $data['contact_name'];
            $data['user_id'] = $this->auth->id;
            $data['status'] = 5;
            $data['type'] = 1;
            unset($data['avatar']);
            unset($data['user_id']);
            unset($data['image']);
            unset($data['verify']);
            unset($data['mobile']);
            unset($data['number']);
            unset($data['category_id']);
            unset($data['auth']);
            $auth = AddressSpot::where('phone',$user['mobile'])->whereNull('deletetime')->where('type',1)->where('shop_id',0)->find();
            if($auth){
                $auth =  AddressSpot::where('phone',$user['mobile'])->whereNull('deletetime')->where('type',1)->where('shop_id',0)->update($data);
            }else{
                $auth = AddressSpot::create($data);
//                if($auth){
//                    $user->spot_id = $auth['id'];
//                    $user->save();
//                }
            }
        }

        $this->success('提交审核成功',$auth);
    }
    public function upload()
    {
        Config::set('default_return_type', 'json');

        //必须还原upload配置,否则分片及cdnurl函数计算错误
        Config::load(APP_PATH . 'extra/upload.php', 'upload');

        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }
    }

    public function getJsApiTicket($accessToken)
    {
        $ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$accessToken}";

        $response = file_get_contents($ticketUrl);
        $result = json_decode($response, true);
        if (isset($result['ticket'])) {
            return $result['ticket'];
        } else {

            return null;
        }
    }
    public function getSignature($jsapiTicket, $url) {
        $timestamp = time();
        $nonceStr = $this->generateNonceStr();

        $string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
        $signature = sha1($string);
        $data = (new WanlPay())->getPublicConfig('wechat');
        return [
            'appId' => $data['app_id'],
            'timestamp' => $timestamp,
            'nonceStr' => $nonceStr,
            'signature' => $signature
        ];
    }
    public function getJsApiConfig()
    {
        $url = $this->request->get('url');

        $accessToken = $this->getAccessToken();
        if ($accessToken) {
            $jsapiTicket = $this->getJsApiTicket($accessToken);
            if ($jsapiTicket) {
                $signatureData = $this->getSignature($jsapiTicket, $url);
                $this->success('获取成功',$signatureData);
            } else {
                $this->error(__('没获取到jsapi_ticket'));
            }
        } else {
            $this->error(__('没获取到accesstoken'));
        }
    }
    public function generateNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public  function getAccessToken() {
        $data = (new WanlPay())->getPublicConfig('wechat');
        $accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$data['app_id']}&secret=397d42b98fd9bc07df5eb2a6296f7bca";

        $response = file_get_contents($accessTokenUrl);
        $result = json_decode($response, true);

        if (isset($result['access_token'])) {
            return $result['access_token'];
        } else {
            // 处理获取 access_token 失败的情况
            return null;
        }
    }
    public function urlPoints()
    {
        $data = $this->request->param();
        $ticket = Tickets::where('id',$data['ticket_id'])->find();
        $third = Third::where('user_id',$this->auth->id)->find();
        $proportion = $this->proportion($ticket);
        //如果是同一用户那么加积分
        if($ticket['unionid'] == $third['unionid'] ){
            if($ticket['is_add_integrals'] != 0){
                $this->success('成功',0);
            }
            // 计算积分，四舍五入
            $points = round($ticket['money'] * $proportion);
            $user = \app\admin\model\User::where('id',$this->auth->id)->find();
            $before = $user['score'];
            $user->score = $before+$points;
            $user->save();
            //积分记录
            $this->pointsLog($points,$before,$before+$points,'通过公众号点击');
            $this->success('成功',1);
        }
        $this->success('成功',0);
    }
    public function proportion($ticket)
    {
        $proportion = 0;
        //获取添加积分比例
        $dataList = PayIntegral::select();
        foreach ($dataList as $data) {
            // 检查 pay_annual 是否与 year 匹配
            if ($ticket['pay_annual'] == $data['year']) {
                // 将 date 类型的 time 转换为时间戳 (假设 $data['time'] 是 Y-m-d 格式)
                $dataTime = strtotime($data['time']);
                // 检查 payment_time 是否小于 dataTime
                if ($ticket['payment_time'] < $dataTime) {
                    // 返回符合条件的 proportion
                    return $data['proportion'];
                }
            }
        }
        return $proportion;
    }
    //输入户号与交易单号添加积分
    public function addPoints()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $ticket = Tickets::where('id',$id)
            ->find();
        $proportion = $this->proportion($ticket);
        if($proportion<0){
            $this->error(__('此条记录暂时是无法添加积分'));
        }
        if($ticket['is_add_integrals'] != 0){
            $this->error(__('此条记录已经添加过积分'));
        }
        // 计算积分，四舍五入
        $points = round($ticket['money'] * $proportion);
        $user = \app\admin\model\User::where('id',$this->auth->id)->find();
        $before = $user['score'];
        $user->score = $before+$points;
        $user->save();
        $ticket->is_add_integrals = 1;
        $log = $this->pointsLog($points,$before,$before+$points,'查询缴费单');
        $ticket->score_log_id = $log['id'];
        $ticket->save();
        $this->success('成功',1);
    }
    public function chaPoints()
    {
        $data = $this->request->param();
        $card_number = $data['card_number'];
        $invoice_no = $data['invoice_no'];
        $ticket = Tickets::where('card_number',$card_number)
            ->whereRaw('RIGHT(invoice_no, 4) = :invoice_no', ['invoice_no' => $invoice_no])
            ->find();
        if($ticket){
            $this->success('成功',$ticket);
        }else{
            $this->error(__('没找到此缴费记录'));
        }
    }
    public function pointsLog($score,$before,$after,$memo)
    {
        $log = ScoreLog::create([
            'user_id'=>$this->auth->id,
            'score'=>$score,
            'before'=>$before,
            'after'=>$after,
            'memo'=>$memo,
        ]);
        return $log;
    }
    public function pointsList()
    {
        $userId = $this->auth->id;
        $tickets = Tickets::alias('t')
            ->join('user_score_log usl', 't.score_log_id = usl.id')
            ->where('usl.user_id', $userId)
            ->order('usl.createtime','desc')
            ->field('t.*, usl.*, t.createtime as ticket_createtime, usl.createtime as scorelog_createtime')
            ->select();
        foreach ($tickets as $ticket){
            $ticket['pick_time'] = date("Y-m-d H:i:s", $ticket['scorelog_createtime']);
        }
        $this->success('成功',$tickets);
    }
}